/**
 * 获取当前页面路由的 path 路径和 redirectPath 路径
 * path 如 ‘/pages/login/index’
 * redirectPath 如 ‘/pages/demo/base/route-interceptor’
 */
export function currRoute() {
  return getUrlObj(getFullPath());
}

/**
 * 获取页面完整地址，包含参数
 * @returns
 */
export function getFullPath() {
  // getCurrentPages() 至少有1个元素，所以不再额外判断
  const lastPage = getCurrentPages().slice(-1)[0];
  const currRoute = (lastPage as any)?.$page;
  if (!currRoute)
    return '';
  // 经过多端测试，只有 fullPath 靠谱，其他都不靠谱
  const { fullPath } = currRoute as { fullPath: string };
  // eg: /pages/login/index?redirect=%2Fpages%2Fdemo%2Fbase%2Froute-interceptor (小程序)
  // eg: /pages/login/index?redirect=%2Fpages%2Froute-interceptor%2Findex%3Fname%3Dfeige%26age%3D30(h5)
  return fullPath;
}

/**
 * 解析 url 得到 path 和 query
 * 比如输入url: /pages/login/index?redirect=%2Fpages%2Fdemo%2Fbase%2Froute-interceptor
 * 输出: {path: /pages/login/index, query: {redirect: /pages/demo/base/route-interceptor}}
 */
export function getUrlObj(url: string) {
  const [path, queryStr] = url.split('?');

  if (!queryStr) {
    return {
      path,
      query: {}
    };
  }
  const query: Record<string, string> = {};
  queryStr.split('&').forEach(item => {
    const [key, value] = item.split('=');
    query[key] = ensureDecodeURIComponent(value); // 这里需要统一 decodeURIComponent 一下，可以兼容h5和微信
  });
  return { path, query };
}

function ensureDecodeURIComponent(url: string): string {
  try {
    let prev = url;
    let decoded = decodeURIComponent(url);
    while (decoded !== prev) {
      prev = decoded;
      decoded = decodeURIComponent(decoded);
    }
    return decoded;
  }
  // eslint-disable-next-line unused-imports/no-unused-vars
  catch (e) {
    return url;
  }
}

/**
 * 拼接地址参数
 * @param query 地址参数
 * @returns
 */
export function buildQueryString(query: Record<string, any>) {
  const queryStr = Object.keys(query).map(key => {
    return `${key}=${encodeURIComponent(query[key])}`;
  }).join('&');
  return queryStr;
}

/**
 * 拼接地址参数
 * @param url 原始地址
 * @param query 新的参数
 * @returns
 */
export function withQueryString(url: string, query: Record<string, any>) {
  // 获取url 中的原始参数
  const { query: originQuery } = getUrlObj(url);
  const queryStr = buildQueryString({ ...originQuery, ...query });
  return `${url}?${queryStr}`;
}
